
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
using System.Globalization;
using System.Linq;

namespace ABA
{
    public class FGUIWinWnd : EditorWindow
    {
        private List<SettingItem> settingItemList;
        private Vector2 scrollPos;
        private GUIStyle titleStyle;

        private GUIStyle infoStyle;

        string winNameInput = "";   
        string pkgNameInput = "";   
        E_FGUIWIN_ZINDEX zindex = E_FGUIWIN_ZINDEX.DIALOG; 

        [MenuItem("ABA/FGUIWin工具", false, 1)]
        public static void FGUIWinTool()
        {
            GetWindow<FGUIWinWnd>(false, "FGUIWin工具", true);
        }

        private void Awake()
        {
        }
        private void OnGUI()
        {
            // 配置目录
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("打开设置", GUILayout.Width(90)))
            {
                SettingWnd.ShowWindow(Path_FGUIWin.TAG);
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(20);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(20);
            GUILayout.Label("FGUIWin包名", GUILayout.Width(80));
            GUILayout.Space(20);
            pkgNameInput = GUILayout.TextField(pkgNameInput);  
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(130);
            GUILayout.Label("FGUI工程里面包的名字，如果没有会自动创建一个");
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(20);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(20);
            GUILayout.Label("FGUIWin名称", GUILayout.Width(80));
            GUILayout.Space(20);
            winNameInput = GUILayout.TextField(winNameInput);  
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(130);
            GUILayout.Label("FGUI工程里面一级导出组件的名字: battle, login, ...");
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(20);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(20);
            GUILayout.Label("FGUIWin类型", GUILayout.Width(80));
            GUILayout.Space(20);
            zindex = (E_FGUIWIN_ZINDEX)EditorGUILayout.EnumPopup(zindex);  
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(130);
            GUILayout.Label("如果是全屏选VIEW, 弹框选DIALOG，特殊组件选COMPONENT");
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(50);
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button($"生成FGUIWin", GUILayout.Height(50)))
            {
                if (String.IsNullOrEmpty(winNameInput) || String.IsNullOrEmpty(pkgNameInput)){
                    EditorUtility.DisplayDialog("提示", "请输入FGUIWin包名或名称", "好吧");                
                }
                else
                {
                    GenFGUIWin();
                }
            }
            EditorGUILayout.EndHorizontal();
        }

        void GenFGUIWin()
        {
            var strWinName = winNameInput.ToLower();
            var strPkgName = pkgNameInput.ToLower();
            var pkgPath = Path_FGUIWin.FGUIPrjFolder + "/assets/" + strPkgName;

            bool hasExtension = Directory.GetFiles(Path_FGUIWin.FGUIPrjFolder, "*", SearchOption.TopDirectoryOnly).Any(file => Path.GetExtension(file) == ".fairy");
            if (!hasExtension)
            {
                EditorUtility.DisplayDialog("提示", "请设置FGUI工程路径!", "好吧");
                return;
            }

            if (!Directory.Exists(pkgPath))
            {
                Directory.CreateDirectory(pkgPath);

                var builder = new StringBuilder();
                builder.Append(pkg_Template);
                Guid guid = Guid.NewGuid();
                string uuid = guid.ToString().Substring(0, 8);

                builder.Replace("{PKG_ID}", uuid);
                string result = builder.ToString();

                File.WriteAllText(pkgPath + "/package.xml", result);   
            }

            var strWinNameExt = strWinName + (zindex == E_FGUIWIN_ZINDEX.VIEW ? "_win" : "_dlg");
            var winPath = Path_FGUIWin.FGUIPrjFolder + "/assets/" + strPkgName + "/" + strWinNameExt + ".xml";
            if (!File.Exists(winPath))
            {
                var builder = new StringBuilder();
                builder.Append(win_Template);

                string strSize = "800,600";
                if(zindex == E_FGUIWIN_ZINDEX.VIEW)
                {
                    strSize = GameConf.DESIGN_RESOLUTION_X + "," + GameConf.DESIGN_RESOLUTION_Y;
                }
                else
                {
                    if(GameConf.DESIGN_RESOLUTION_X == 1080 || GameConf.DESIGN_RESOLUTION_Y == 1080){
                        if(GameConf.DESIGN_RESOLUTION_X > GameConf.DESIGN_RESOLUTION_Y){
                            strSize = 1500 + "," + 900;
                        }
                        else{
                            strSize = 900 + "," + 1500;
                        }                        
                    }
                    else{
                        if(GameConf.DESIGN_RESOLUTION_X > GameConf.DESIGN_RESOLUTION_Y){
                            strSize = 960 + "," + 600;
                        }
                        else{
                            strSize = 600 + "," + 960;
                        } 
                    }
                }
                builder.Replace("{WIN_SIZE}", strSize);

                string result = builder.ToString();
                File.WriteAllText(winPath, result);

                // C#
                string cpkgDirName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strPkgName);
                string cDirName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strWinName);
                var cDirPath = Path_FGUIWin.GenCSharpFolder + "/" + cpkgDirName;
                if (!Directory.Exists(cDirPath))
                {
                    Directory.CreateDirectory(cDirPath);
                }

                string className = cDirName + (zindex == E_FGUIWIN_ZINDEX.VIEW ? "Win" : "Dlg");
                string cPath = cDirPath + "/" + className + ".cs";
                if(!File.Exists(cPath))
                {
                    var builder1 = new StringBuilder();
                    if(zindex == E_FGUIWIN_ZINDEX.VIEW)
                        builder1.Append(c_view_Template);
                    else
                        builder1.Append(c_dlg_Template);

                    builder1.Replace("{WIN_NAME}", strWinNameExt.ToUpper());
                    builder1.Replace("{CLASS_NAME}", className);
                    builder1.Replace("{PKG_NAME}", strPkgName);
                    builder1.Replace("{COMP_NAME}", strWinNameExt);
                    builder1.Replace("{ZINDEX_NAME}", zindex.ToString());
                    string result1 = builder1.ToString();

                    File.WriteAllText(cPath, result1);

                    EditorUtility.DisplayDialog("提示", $"成功生成！", "好吧");
                }
                else{
                    EditorUtility.DisplayDialog("警告", $"已经存在{cPath}!!!", "好吧"); 
                }
            }
            else{
                EditorUtility.DisplayDialog("警告", $"已经存在{strWinName}的FGUIWin!!!", "好吧"); 
            }
        }

        public const string pkg_Template = 
@"<?xml version=""1.0"" encoding=""utf-8""?>
<packageDescription id=""{PKG_ID}"">
  <resources/>
</packageDescription>        
";

        public const string win_Template = 
@"<?xml version=""1.0"" encoding=""utf-8""?>
<component size=""{WIN_SIZE}""/>       
";

        public const string c_view_Template = @"
using System;
using System.Collections.Generic;
using UnityEngine;

namespace ABA
{
    public partial class FGUIWinConf
    {
        public static FGUIWinInfo {WIN_NAME} = new FGUIWinInfo
        {
            cls_name = typeof({CLASS_NAME}).Name,
            pkg_name = ""{PKG_NAME}"",
            comp_name = ""{COMP_NAME}"",
            zindex = E_FGUIWIN_ZINDEX.{ZINDEX_NAME},
            ani = false
        }; 
    }

    public class {CLASS_NAME} : FGUIWindow
    {
        public {CLASS_NAME}(FGUIWinInfo info) : base(info){}
        protected override void OnInit()
        {
            base.OnInit();

            // contentPane.GetChild(""backBtn"").asButton.onClick.Set(()=>{
            //     Module.inst.Pop();
            // });
        }
        // [FGUIWinDataEvent(DataField.hp)]
        // public void HpIntChange(DataIntChange e){
        // }
        public override void InitAfterShow()
        {

        }
        protected override void OnDispose()
        {
            base.OnDispose();
        }
    }
}    
";

        public const string c_dlg_Template = @"
using System;
using System.Collections.Generic;
using UnityEngine;

namespace ABA
{
    public partial class FGUIWinConf
    {
        public static FGUIWinInfo {WIN_NAME} = new FGUIWinInfo
        {
            cls_name = typeof({CLASS_NAME}).Name,
            pkg_name = ""{PKG_NAME}"",
            comp_name = ""{COMP_NAME}"",
            zindex = E_FGUIWIN_ZINDEX.{ZINDEX_NAME},
            ani = true
        }; 
    }

    public class {CLASS_NAME} : FGUIWindow
    {
        public {CLASS_NAME}(FGUIWinInfo info) : base(info){}
        protected override void OnInit()
        {
            base.OnInit();
            Center();
            SetBlockEvent(true, () =>{
                FGUIManager.inst.HideWindow(FGUIWinConf.{WIN_NAME});
            });
        }
        // [FGUIWinDataEvent(DataField.hp)]
        // public void HpIntChange(DataIntChange e){
        // }
        public override void InitAfterShow()
        {

        }
        protected override void OnDispose()
        {
            base.OnDispose();
        }
    }
}  
";


    }
}
